package com.lvtn.adsonandroid;

import java.io.File;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;




import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
 
public class PostNews extends Activity {
 
    private static final int SELECT_FILE1 = 1;
  //  private static final int SELECT_FILE2 = 2;
   // String selectedPath1 = "NONE";
   // String selectedPath2 = "NONE";
    String cate, mEmail;
    String numI , img;
   // String[] arr;
    //HttpEntity resEntity;
	private String selectedImagePath;
	MyImageAdapter adapter;
	ArrayList<String> arrList=null;
	String []arr;
	int i = 0;
    TextView tv, res;
    GridView grid;
    ProgressDialog progressDialog;
    Button b1,b2,b3;
    HttpEntity resEntity;
    EditText title, price, decribe;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_news);
 
       // tv = (TextView)findViewById(R.id.tv);
        //res = (TextView)findViewById(R.id.res);
        RadioGroup g = (RadioGroup) findViewById(R.id.radioGroup);
        //---------get Intent--------------
        Intent intent = getIntent();
		mEmail = intent.getStringExtra(ManageActivity.EXTRA_MESSAGE);
        
	    img="image";
	    numI="khong";
       // tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
        grid = (GridView) findViewById(R.id.gridView);
        title = (EditText) findViewById(R.id.title1);
        price = (EditText) findViewById(R.id.price);
        decribe = (EditText) findViewById(R.id.decribe);
        b1 = (Button) findViewById(R.id.btn_browser);
        //b2 = (Button)findViewById(R.id.Button02);
        b3 = (Button)findViewById(R.id.upload);
        arr = new String[20];
		arrList = new ArrayList<String>();
		adapter = new MyImageAdapter(this,arr);
		//Log.d("aaaaaaaaaaaaaaabbbbbbb","ccccc");
		grid.setAdapter(adapter);
		
		//------Radio Group--------------
		//int index = g.getCheckedRadioButtonId();
		
		RadioButton sale = (RadioButton) findViewById(R.id.sale);
		RadioButton buy = (RadioButton) findViewById(R.id.buy);
	//	sale.clear
		if (sale.isChecked()) {
			Log.d("cate","=2");
			cate = "1";
		}
		else if (buy.isChecked())  {
			Log.d("cate","=2");
			cate = "2";
		}
		
		//-------------button browser--------------
        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(SELECT_FILE1);
            }
        });

        
        //-------------Button Đăng tin------------------
        b3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               // if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) || !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
                    progressDialog = ProgressDialog.show(PostNews.this, "", "Uploading files to server.....", false);
                     Thread thread=new Thread(new Runnable(){
                            public void run(){
                                doFileUpload();
                                runOnUiThread(new Runnable(){
                                    public void run() {
                                        if(progressDialog.isShowing())
                                            progressDialog.dismiss();
                                    }
                                });
                            }
                    });
                    thread.start();
               // }else{
                      //      Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
              //  }
            }
            
        });
 
    }
 
    public void openGallery(int req_code){
 
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
   }
 
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
 
        if (resultCode == RESULT_OK) {
        	if (requestCode == SELECT_FILE1) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                System.out.println("Image Path : " + selectedImagePath);
                arr[i]=(selectedImagePath);
                i++;
               // for(int i=0;i< arrList.size(); i++){
                //img = "img"+ i;
              //  img0.setImageBitmap(BitmapFactory.decodeFile(arr[i].toString()));
             //   }
        		adapter.notifyDataSetChanged();
                //Log.d("aaaaaa",arr[0]);
               // Log.d("aaaaaaaaaaaaaaabbbbbbb",adapter.toString());
        }
        }
    }
 
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
 
    private void doFileUpload(){
    	String name = title.getText().toString();
		String cost = price.getText().toString();
		String decription = decribe.getText().toString(); 
		int size = arr.length;
		
       // File file1 = new File(arr[0]);
        //File file2 = new File(arr[1]);
        String urlString = "http://10.0.2.2/android/news_upload.php";
        
        try
        {
             HttpClient client = new DefaultHttpClient();
             HttpPost post = new HttpPost(urlString);
             MultipartEntity reqEntity = new MultipartEntity();
             reqEntity.addPart("avarta", new StringBody("0"));
             if (i!=0){
         		FileBody[] b;
         		b = new FileBody[20];
         		File[] a;
         		a = new File[20];
         		//a[0] = new File(arr[0]);
         		
         		for(int j=0;j < i;j++) {
         		  a[j]= new File(arr[j]);
         		  Log.d("so luong anh", "hhhhhhhh");
         		}
         		
     		for(int k=0;k < i;k++){
    			b[k]= new FileBody(a[k]);
    		}
     		Log.d("so luong anh","bbbb1");   
             
             for(int h=0;h < i;h++){
            	 numI = h+img;
            	 Log.d("so luong anh",numI);
            	 reqEntity.addPart(img+h, b[h]);
     		}
             }
            // reqEntity.addPart("image1", b[0]);
            // reqEntity.addPart("uploadedfile2", b[1]);
             reqEntity.addPart("title", new StringBody(name));
             reqEntity.addPart("price", new StringBody(cost));
             reqEntity.addPart("decribe", new StringBody(decription));
             reqEntity.addPart("category", new StringBody(cate));
             reqEntity.addPart("numImg", new StringBody(numI));
             reqEntity.addPart("email", new StringBody(mEmail));
            // reqEntity.addPart("user", new StringBody("User"));
             post.setEntity(reqEntity);
             HttpResponse response = client.execute(post);
             resEntity = response.getEntity();
             final String response_str = EntityUtils.toString(resEntity);
             if (resEntity != null) {
                 Log.i("RESPONSE",response_str);
                 runOnUiThread(new Runnable(){
                        public void run() {
                             try {
                                //res.setTextColor(Color.GREEN);
                               // res.setText("n Response from server : n " + response_str);
                                Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                           }
                    });
             }
            // i=0;
        }
        catch (Exception ex){
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
      }
	 /**
     * Adapter for our image files.
     */
	public class MyImageAdapter extends BaseAdapter {
		private Context mContext;
		private String []mThumbIds;
		public MyImageAdapter(Context c){
			mContext=c;
		}
		public MyImageAdapter(Context c,String []arrIds){
			mContext=c;
			mThumbIds=arrIds;
		}
		public int getCount() 
		{
			return mThumbIds.length;	
		}
		public Object getItem(int arg0) 
		{
			return arg0;
		}
		public long getItemId(int arg0) 
		{
			return arg0;
		}
		/**
		 * Cần override lại hàm này để hiển thị hình ảnh
		 */
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			ImageView imgView;
			if(convertView==null){
				imgView=new ImageView(mContext);
				//can chỉnh lại hình cho đẹp
				
				imgView.setLayoutParams(new GridView.LayoutParams(85, 85));
				imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				imgView.setPadding(2, 2, 2, 2);
				//imgView.setImageURI(mThumbIds[arg0]);
			}else{
				imgView=(ImageView) convertView;
			}
			//lấy đúng vị trí hình ảnh được chọn
			//gán lại ImageResource));
			imgView.setImageBitmap(BitmapFactory.decodeFile(mThumbIds[arg0]));
			return imgView;
		}
	}
}